﻿using System;
using DotNetOpenAuth.OAuth.ChannelElements;
using DotNetOpenAuth.OAuth.Messages;

namespace RoketSolutions.SP2010.LinkedInWebPart.Authorization
{
    public class SPTokenManager : ILinkedInTokenManager
    {
        private readonly TokenSource source;

        public SPTokenManager(TokenSource tokenSource)
        {
            source = tokenSource;
            ConsumerKey = source.ConsumerKey;
            ConsumerSecret = source.ConsumerSecret;
        }

        #region IConsumerTokenManager members

        public string GetTokenSecret(string token)
        {
            return source.FindSecret(token);
        }

        public void StoreNewRequestToken(UnauthorizedTokenRequest request, ITokenSecretContainingMessage response)
        {
            var requestToken = new Token { Key = response.Token, Secret = response.TokenSecret, TokenType = TokenType.RequestToken };
            source.SetToken(requestToken);
        }

        public void ExpireRequestTokenAndStoreNewAccessToken(string consumerKey, string requestToken, string accessToken, string accessTokenSecret)
        {
            var oAccessToken = new Token { Key = accessToken, Secret = accessTokenSecret, TokenType = TokenType.AccessToken };
            source.RemoveToken(TokenType.RequestToken);
            source.SetToken(oAccessToken);
        }

        public TokenType GetTokenType(string token)
        {
            throw new NotImplementedException();
        }

        public string ConsumerKey { get; private set; }

        public string ConsumerSecret { get; private set; }

        #endregion

        public Token GetAccessToken()
        {
            var token = source.GetToken(TokenType.AccessToken);
            return token;
        }

        public void RemoveRequestToken()
        {
            source.SetToken(new Token
            {
                TokenType = TokenType.RequestToken,
                Key = string.Empty,
                Secret = string.Empty
            });
        }

        public void RemoveAccessToken()
        {
            source.SetToken(new Token
                                                        {
                                                            TokenType = TokenType.AccessToken,
                                                            Key = string.Empty,
                                                            Secret = string.Empty
                                                        });
        }
    }
}